package com.spark.sql

import org.apache.spark.SparkConf
import org.apache.spark.sql._
import org.apache.spark.sql.expressions.Aggregator

/**
  *
  * @author Pop
  * @date 2022/7/20 22:48
  */
object Spark05_SparkSql_JDBC {
  def main(args: Array[String]): Unit = {

    // 创建SparkSql的运行环境
    val sparkSql: SparkConf = new SparkConf().setMaster("local[*]").setAppName("sparkSql")
    val session: SparkSession = SparkSession.builder().config(sparkSql).getOrCreate()
    import session.implicits._
    //读取jdbc数据
    val df: DataFrame = session.read.format("jdbc")
      .option("url", "jdbc:mysql://localhost:3306/spark_mysql")
      .option("driver", "com.mysql.cj.jdbc.Driver")
      .option("user", "root")
      .option("password", "root")
      .option("dbtable", "student").load()
    df.show()

    //保存数据,到另一张表
    df.write.format("jdbc")
      .option("url", "jdbc:mysql://localhost:3306/spark_mysql")
      .option("driver", "com.mysql.cj.jdbc.Driver")
      .option("user", "root")
      .option("password", "root")
      .option("dbtable", "student1").mode(SaveMode.Append)
        .save()
    session.close()
  }

}
